import React, { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Form, Button, Input } from 'antd-mobile'
import '../assets/css/loginView.css'
import '../assets/css/laobanInfo.css'
import store from '../redux/store'
import { saveToken } from '../redux/action'

export default function Info() {
  let arr = []
  const location = useLocation()
  let [chooseUrl, setUrl] = useState("")
  let choosePic = React.createRef()
  for (let i = 1; i <= 20; i++) {
    arr.push({
      icon: require(`../assets/images/${10000 + i}.webp`)
    })
  }
  function chooseAvatar(e) {
    choosePic.current.src = e.target.src
    setUrl(e.target.src)
  }
  return (
    <div>
      <div className='header'>{location.state.identity}信息完善</div>
      <p className='avatarTitle'>请选择头像</p>
      <div>
        已选择头像: <img src="" alt="" ref={choosePic} width="8%" />
      </div>
      <div className="avatarBox">
        <ul>
          {
            arr.map((item, index) => (
              <li key={index}>
                <img src={item.icon} alt="" width="50%" onClick={(e) => { chooseAvatar(e) }} />
                <p>头像{index + 1}</p>
              </li>
            ))
          }
        </ul>
      </div>
      {location.state.identity === "老板" ? LaobanInfo({ avatar: chooseUrl }) : DashenInfo({ avatar: chooseUrl })}
    </div>
  )
}

function LaobanInfo(props) {
  const [form] = Form.useForm()
  let location = useLocation()
  let navigate = useNavigate()
  return (<div>
    <Form
      layout='horizontal'
      form={form}
      footer={
        <Button block type='submit' color='success' size='large' onClick={() => {
          let InfoMsg = {
            avatar: getBase64(props.avatar),
            job: form.getFieldValue().job,
            companyName: form.getFieldValue().companyName,
            positionSalary: form.getFieldValue().positionSalary,
            jobRequirements: form.getFieldValue().jobRequirements,
            laobanName: location.state.name
          }
          let result = sendInfo(InfoMsg, 'http://127.0.0.1:8080/laoban/addInfo')
          if (result) navigate('/main/center', { state: { title: '员工列表' } })
        }}>
          保存
        </Button>
      }
    >
      <Form.Item name="job" label="招聘职位:">
        <Input className='ipt' />
      </Form.Item>
      <Form.Item name="companyName" label="公司名称:">
        <Input className='ipt' />
      </Form.Item>
      <Form.Item name="positionSalary" label="职位薪资:">
        <Input className='ipt' />
      </Form.Item>
      <Form.Item name="jobRequirements" label="职位要求:">
        <Input className='ipt' />
      </Form.Item>
    </Form>
  </div>)
}

function DashenInfo(props) {
  const [form] = Form.useForm()
  let navigate = useNavigate()
  let location = useLocation()
  return (<div>
    <Form
      layout='horizontal'
      form={form}
      footer={
        <Button block type='submit' color='success' size='large' onClick={async () => {
          let InfoMsg = {
            avatar: getBase64(props.avatar),
            dashenName: location.state.name,
            job: form.getFieldValue().job,
            personalIntroduction: form.getFieldValue().personalIntroduction
          }
          let result = await sendInfo(InfoMsg, 'http://127.0.0.1:8080/dashen/addInfo')
          if (result) navigate("/main/center", { state: { title: '老板列表' } })
        }}>
          保存
        </Button>
      }
    >
      <Form.Item name="job" label="求职岗位:">
        <Input className='ipt' />
      </Form.Item>
      <Form.Item name="personalIntroduction" label="个人介绍:">
        <Input className='ipt' />
      </Form.Item>
    </Form>
  </div>)
}

function getImage2Base64(img) {
  let canvas = document.createElement('canvas')
  canvas.width = img.width
  canvas.height = img.height
  let ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, img.width, img.height)
  let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
  let dataURL = canvas.toDataURL('image/' + ext)
  return dataURL
}

function getBase64(imgSrc) {
  // let base64 = ''
  let img = new Image()
  img.src = imgSrc
  // img.onload = () => {
  //   base64 = getImage2Base64(img)
  // }
  return getImage2Base64(img)
}

async function sendInfo(InfoMsg, url) {
  let res = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(InfoMsg)
  }).then(res => res.json())
  if (res.code != 1) {
    alert(res.msg)
    return
  }
  store.dispatch(saveToken(res.data))
  return true
}
